package com.doris.media.picker.activity

import android.app.ActivityOptions
import android.content.Intent
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.doris.media.picker.R
import com.doris.media.picker.adapter.BaseMediaPickerAdapter
import com.doris.media.picker.adapter.MediaPickerAdapter
import com.doris.media.picker.adapter.MediaPickerListener
import com.doris.media.picker.adapter.MediaPickerRowAdapter
import com.doris.media.picker.model.MediaModel
import com.doris.media.picker.model.MediaPickerConfig
import com.doris.media.picker.model.MediaPickerParameter
import com.doris.media.picker.model.MediaPickerPreviewParameter
import com.doris.media.picker.utils.MediaUtils
import com.doris.media.picker.utils.permission.MyPermissionsUtils
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.qmuiteam.qmui.arch.QMUIActivity
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.android.synthetic.main.media_picker_activity.*

class MediaPickerActivity : QMUIActivity(), MediaPickerListener {

    private var mType = "图片"
    private var mPageIndex = 0
    private lateinit var mAdapter: BaseMediaPickerAdapter
    private lateinit var mParameter: MediaPickerParameter

    private var mTipDialog: QMUITipDialog? = null

    private var mMediaPlayer: MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.media_picker_activity)
        initParameter()
        initStatus()
        initTopBar()
        initPage()
        initList()
        if (hasPermission()) {
            initMedia()
        } else {
            mediaPicker_loading.showNoPermission("需要请求存储权限，用于加载您的本地${mType}，实现${mType}的选择")
        }
    }

    private fun initParameter() {
        mParameter = intent.getParcelableExtra(MediaPickerConfig.MEDIA_PICKER)
            ?: MediaPickerParameter()
        val pickerData =
            intent.getParcelableArrayListExtra<MediaModel>(MediaPickerConfig.MEDIA_PICKER_DATA)
        if (!pickerData.isNullOrEmpty()) {
            mParameter.pickerData.clear()
            mParameter.pickerData.addAll(pickerData)
        }
        val pickerMimeType =
            intent.getStringArrayListExtra(MediaPickerConfig.MEDIA_PICKER_MIME_TYPE)
        if (!pickerMimeType.isNullOrEmpty()) {
            mParameter.mimeTyp.clear()
            mParameter.mimeTyp.addAll(pickerMimeType)
        }
    }

    private fun initStatus() {
        if (mParameter.statusTheme == MediaPickerConfig.STATUS_THEME_DARK) {
            QMUIStatusBarHelper.setStatusBarDarkMode(this)
        } else {
            QMUIStatusBarHelper.setStatusBarLightMode(this)
        }
    }

    private fun initTopBar() {
        mType = when (mParameter.type) {
            MediaPickerConfig.TYPE_VIDEO -> "视频"
            MediaPickerConfig.TYPE_AUDIO -> "音频"
            else -> "图片"
        }
        // 返回按钮
        if (mParameter.backText.isEmpty()) {
            val backBtn = if (mParameter.backIcon == R.mipmap.media_picker_back)
                mediaPicker_topBar.addLeftBackImageButton()
            else
                mediaPicker_topBar.addLeftImageButton(
                    mParameter.backIcon, R.id.mediaPicker_topBar_back
                )
            backBtn.setOnClickListener { finish() }
        } else {
            val backBtn = mediaPicker_topBar.addLeftTextButton(
                mParameter.backText, R.id.mediaPicker_topBar_back
            )
            if (mParameter.backTextColorRes != R.color.media_picker_topbar_text_btn_color)
                backBtn.setTextColor(
                    ContextCompat.getColorStateList(this, mParameter.backTextColorRes)
                )
            backBtn.setOnClickListener { finish() }
        }
        // 标题
        val titleView = if (mParameter.title.isEmpty()) {
            mediaPicker_topBar.setTitle("选择$mType")
        } else {
            mediaPicker_topBar.setTitle(mParameter.title)
        }
        val defaulTitleColor = ContextCompat.getColor(this, R.color.topBarTitle)
        val titleColor = ContextCompat.getColor(this, mParameter.titleColorRes)
        if (titleColor != defaulTitleColor) {
            titleView.setTextColor(titleColor)
        }
        // 确定按钮
        if (mParameter.sureIcon != 0) {
            val sureBtn = mediaPicker_topBar
                .addRightImageButton(mParameter.sureIcon, R.id.mediaPicker_topBar_sure)
            sureBtn.scaleType = ImageView.ScaleType.CENTER_INSIDE
            sureBtn.setOnClickListener { sure() }
        } else {
            if (mParameter.sureText.isEmpty()) mParameter.sureText = "确定"
            val sureBtn = mediaPicker_topBar
                .addRightTextButton(mParameter.sureText, R.id.mediaPicker_topBar_sure)
            if (mParameter.sureTextColorRes != R.color.media_picker_topbar_text_btn_color)
                sureBtn.setTextColor(
                    ContextCompat.getColorStateList(this, mParameter.sureTextColorRes)
                )
            sureBtn.setOnClickListener { sure() }
        }
        // 标题背景图片、颜色
        if (mParameter.topBarRes != 0) {
            mediaPicker_topBar.setBackgroundResource(mParameter.topBarRes)
        } else if (mParameter.topBarColorRes != R.color.topBar) {
            mediaPicker_topBar.setBackgroundColor(
                ContextCompat.getColor(this, mParameter.topBarColorRes)
            )
        }
    }

    private fun initPage() {
        if (mParameter.pageRes != 0) {
            mediaPicker_pager.setImageResource(mParameter.pageRes)
        } else {
            mediaPicker_pager.visibility = View.GONE
            if (mParameter.pageColor != Color.WHITE)
                container_mediaPicker.setBackgroundColor(mParameter.pageColor)
        }

        mediaPicker_loading.setTipColor(mParameter.tipColor)
        if (mParameter.progressColorRes != R.color.colorAccent) {
            mediaPicker_loading.setProgressColor(
                ContextCompat.getColor(this, mParameter.progressColorRes)
            )
        }
        if (mParameter.permissionBtnColorRes != R.color.colorAccent) {
            mediaPicker_loading.setPermissionBtnColor(
                ContextCompat.getColor(this, mParameter.permissionBtnColorRes)
            )
        }
        if (mParameter.permissionBtnBorderColorRes != R.color.colorAccent) {
            mediaPicker_loading.setPermissionBtnBorderColor(
                ContextCompat.getColor(this, mParameter.permissionBtnBorderColorRes)
            )
        }

        mediaPicker_loading.setBtnClickListener {
            MyPermissionsUtils.requestPermissionsTurn(this,
                "用于加载您的本地${mType}，实现${mType}的选择。以及应用下载/保存/缓存${mType}等至本地，实现应用的基本功能。",
                object : MyPermissionsUtils.HavePermissionListener {
                    override fun havePermission() {
                        mediaPicker_loading.showLoading()
                        initMedia()
                    }
                }, Permission.WRITE_EXTERNAL_STORAGE)
        }
    }

    private fun initList() {
        if (mParameter.spanCount < 1) mParameter.spanCount = 1
        if (mParameter.spanCount > 5) mParameter.spanCount = 5

        mAdapter = if (mParameter.spanCount == 1) {
            mediaPicker_recycler.layoutManager = LinearLayoutManager(this)
            MediaPickerRowAdapter(mParameter, this)
        } else {
            mediaPicker_recycler.layoutManager =
                GridLayoutManager(this, mParameter.spanCount)
            MediaPickerAdapter(mParameter, this)
        }
        mAdapter.loadMoreModule.isEnableLoadMore = true
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            mPageIndex++
            initMedia()
        }
        (mediaPicker_recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mediaPicker_recycler.adapter = mAdapter
    }

    private fun hasPermission(): Boolean {
        val hasPermission = XXPermissions.isGranted(this, Permission.MANAGE_EXTERNAL_STORAGE)
                || XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)
                || XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE)
        val readMediaPermission = when (mParameter.type) {
            MediaPickerConfig.TYPE_VIDEO ->
                XXPermissions.isGranted(this, Permission.READ_MEDIA_VIDEO)
            MediaPickerConfig.TYPE_AUDIO ->
                XXPermissions.isGranted(this, Permission.READ_MEDIA_AUDIO)
            else ->
                XXPermissions.isGranted(this, Permission.READ_MEDIA_IMAGES)
        }
        return hasPermission || readMediaPermission
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == XXPermissions.REQUEST_CODE) {
            if (hasPermission()) {
                mediaPicker_loading.showLoading()
                initMedia()
            }
        }
    }

    private fun initMedia() {
        when (mParameter.type) {
            MediaPickerConfig.TYPE_VIDEO -> loadVideo()
            MediaPickerConfig.TYPE_AUDIO -> loadAudio()
            else -> loadImage()
        }
    }

    private fun loadImage() {
        MediaUtils.loadImage(
            this, mParameter.mimeTyp, mParameter.minSize,
            mParameter.maxSize, mParameter.folder, mParameter.pageSize, mPageIndex
        ) { loadOver(it) }
    }

    private fun loadVideo() {
        MediaUtils.loadVideo(
            this, mParameter.mimeTyp, mParameter.minSize,
            mParameter.maxSize, mParameter.folder, mParameter.pageSize, mPageIndex
        ) { loadOver(it) }
    }

    private fun loadAudio() {
        MediaUtils.loadAudio(
            this, mParameter.mimeTyp, mParameter.minSize,
            mParameter.maxSize, mParameter.folder, mParameter.pageSize, mPageIndex
        ) { loadOver(it) }
    }

    private fun loadOver(it: ArrayList<MediaModel>) {
        if (it.isEmpty()) {
            if (mPageIndex == 0) mediaPicker_loading.showTip("暂无$mType")
            else {
                mAdapter.loadMoreModule.loadMoreEnd(true)
            }
        } else {
            if (mPageIndex == 0) {
                mediaPicker_loading.hide()
                mAdapter.setNewInstance(it)
            } else {
                mAdapter.addData(it)
                mAdapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

    private fun sure() {
        if (mParameter.min > mAdapter.getPickerSize()) {
            showTip("最少${mParameter.min}${getUnit()}$mType")
            return
        }
        val pickerIntent = Intent()
        pickerIntent.putExtra(MediaPickerConfig.MEDIA_PICKER_DATA, mAdapter.getPickerModel())
        setResult(MediaPickerConfig.MEDIA_PICKER_RESULT_OK, pickerIntent)
        finish()
    }

    override fun onPreview(view: View, model: MediaModel) {
        val parameter = MediaPickerPreviewParameter()
            .statusTheme(mParameter.statusTheme)
            .path(model.path)
        when (model.type) {
            MediaPickerConfig.TYPE_IMAGE -> {
                val intent = Intent(this, PreviewImageActivity::class.java)
                intent.putExtra(MediaPickerConfig.MEDIA_PICKER_PREVIEW, parameter)
                val options = ActivityOptions.makeSceneTransitionAnimation(
                    this,
                    view, "sharedView"
                ).toBundle()
                this.startActivity(intent, options)
            }
            MediaPickerConfig.TYPE_VIDEO -> {
                PreviewVideoActivity.show(this, parameter)
            }
            MediaPickerConfig.TYPE_AUDIO -> {
                if (mMediaPlayer?.isPlaying == true &&
                    mAdapter.getPlayAudioPosition() == mAdapter.getItemPosition(model)
                ) {
                    stopPlayAudio()
                    mAdapter.updatePlayAudioPosition(-1)
                } else {
                    startPlayAudio(model)
                }
            }
        }
    }

    private fun startPlayAudio(model: MediaModel) {
        try {
            stopPlayAudio()
            mMediaPlayer = MediaPlayer()
            mMediaPlayer?.setDataSource(model.path)
            mMediaPlayer?.setOnPreparedListener { it.start() }
            mMediaPlayer?.setOnCompletionListener {
                mAdapter.updatePlayAudioPosition(-1)
            }
            mMediaPlayer?.isLooping = false
            mMediaPlayer?.prepare()
            mAdapter.updatePlayAudioPosition(mAdapter.getItemPosition(model))
        } catch (e: Exception) {
            e.printStackTrace()
            stopPlayAudio()
            mAdapter.updatePlayAudioPosition(-1)
        }
    }

    private fun stopPlayAudio() {
        mMediaPlayer?.stop()
        mMediaPlayer?.reset()
        mMediaPlayer?.release()
        mMediaPlayer = null
    }

    override fun showMaxTip() {
        showTip("最多${mParameter.max}${getUnit()}$mType")
    }

    private fun getUnit() = if (mParameter.type == MediaPickerConfig.TYPE_IMAGE) "张" else "个"

    private fun showTip(msg: String) {
        dissmissTip()
        mTipDialog = QMUITipDialog.Builder(this)
            .setIconType(QMUITipDialog.Builder.ICON_TYPE_INFO)
            .setTipWord(msg).create()
        mTipDialog?.show()
        Handler(Looper.getMainLooper()).postDelayed({ dissmissTip() }, 1000)
    }

    private fun dissmissTip() {
        if (mTipDialog != null && mTipDialog?.isShowing == true) {
            mTipDialog?.dismiss()
            mTipDialog = null
        }
    }

    override fun onPause() {
        super.onPause()
        stopPlayAudio()
    }

    override fun onDestroy() {
        super.onDestroy()
        dissmissTip()
    }
}